package com.vichat.res.controller;

import com.alibaba.fastjson.JSON;
import com.vichat.common.cache.RedisHelper;
import com.vichat.common.constant.GlobalConstant;
import com.vichat.common.util.*;
import com.vichat.common.vo.Grid;
import com.vichat.common.vo.Json;
import com.vichat.common.vo.PageFilter;
import com.vichat.res.entity.ResConfig;
import com.vichat.res.entity.ResEvent;
import com.vichat.res.entity.ResFile;
import com.vichat.res.service.IResService;
import com.vichat.res.vo.ResFileRequsetVO;
import com.vichat.res.vo.ResFileVO;
import com.vichat.user.controller.BaseController;
import com.vichat.user.entity.UserBasic;
import com.vichat.user.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by 82116 on 2017/12/19.
 */
@Controller
@RequestMapping("/res")
public class ResApiController {
    protected static final Logger logger = LoggerFactory.getLogger(ResApiController.class);
    @Autowired
    HttpServletRequest request;
    @Autowired
    HttpServletResponse response;
    @Autowired
    private IResService resService;
    @Autowired
    private IUserService userService;

    /**
     * 永久存储
     *
     * @param files
     * @return
     */
    @ResponseBody
    @RequestMapping("/fileUpload")
    public Json fileUpload(@RequestParam("file") MultipartFile[] files) {
        Json json = new Json();
        try {
            if (files == null && files.length == 0) {
                throw new Exception("文件不能为空。");
            }
            ResConfig config = resService.getResConfig("Upload");
            if (config == null) {
                throw new Exception("请配置永久存储路径");
            }
            List<ResFile> resFiles = saveFile(files);
            if (!resFiles.isEmpty()) {
                List<ResFileVO> responseRes = new ArrayList<>();
                for (ResFile res : resFiles) {
                    String suffix = FileTypeUtil.getExtensionName(res.getResName());
                    if (GlobalConstant.USABLE_FILE_SUFFIX_LIST.contains(suffix)) {
                        ResFileVO resFileVO = new ResFileVO();
                        res.setStoreUrl(res.getStoreUrl());
                        ResFile resFileFDB = resService.saveOrUpdResFile(res);
                        resFileFDB.setStoreUrl(config.getAttachUrl() + resFileFDB.getStoreUrl());
                        resFileVO.setResId(resFileFDB.getResId());
                        resFileVO.setStoreUrl(resFileFDB.getStoreUrl());
                        responseRes.add(resFileVO);
                    } else {
                        logger.error("文件类型错误");
                    }
                }
                logger.info("返回值为：" + JSON.toJSONString(responseRes));
                json.setObj(responseRes);
            }
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }
        return json;
    }

    /**
     * 事件上报永久存储(取证、录音)
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/fileUploadToEvent")
    public Json fileUploadToEvent(ResFileRequsetVO paramsVO) {
        Json json = new Json();
        try {
            if (NumberUtils.isNullOrZero(paramsVO.getUid())) {
                throw new Exception("uid is required");
            }
            if (StringUtils.isEmpty(paramsVO.getToken())) {
                throw new Exception("token is required");
            }
            UserUtil.checkToken(paramsVO.getToken(), paramsVO.getUid());

            UserBasic userBasicFDB = userService.getUserBasicByUid(paramsVO.getUid());
            if (userBasicFDB == null) {
                throw new Exception("非法用户ID请求");
            }
            paramsVO.setPartyId(userBasicFDB.getPartyId());

            //保存文件
            if (paramsVO.getFiles() != null && paramsVO.getFiles().length != 0) {

                MultipartFile[] files = paramsVO.getFiles();

                ResConfig config = resService.getResConfig("Upload");
                if (config == null) {
                    throw new Exception("请配置永久存储路径");
                }

                checkFileType(files);

                List<ResFile> resFiles = saveFile(files);
                if (!resFiles.isEmpty()) {
                    List<ResFileVO> responseRes = new ArrayList<>();
                    for (ResFile res : resFiles) {
                        res.setStoreUrl(res.getStoreUrl());
                        ResFile resFileFDB = resService.saveOrUpdResFile(res);
                        resFileFDB.setStoreUrl(config.getAttachUrl() + resFileFDB.getStoreUrl());

                        ResFileVO resFileVO = new ResFileVO();
                        resFileVO.setResId(resFileFDB.getResId());
                        resFileVO.setStoreUrl(resFileFDB.getStoreUrl());
                        responseRes.add(resFileVO);
                    }

                    resService.saveResEvent(paramsVO, responseRes);
                    logger.info("返回值为：" + JSON.toJSONString(responseRes));
                }
            } else {
                ResEvent resEvent = resService.saveResEvent(paramsVO, null);
                logger.info("返回值为：" + JSON.toJSONString(resEvent));
            }
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setCode(-9);
        }
        return json;
    }

    private void checkFileType(MultipartFile[] files) throws Exception {
        for (MultipartFile res : files) {
            String resType = FileTypeUtil.getFileSuffix(res.getOriginalFilename());
            if (!GlobalConstant.USABLE_FILE_SUFFIX_LIST.contains(resType.toLowerCase())) {
                throw new Exception("文件类型错误");
            }
        }
    }

    /**
     * 临时存储
     *
     * @param files
     * @return
     */
    @ResponseBody
    @RequestMapping("/tempFileUpload")
    public Json tempFileUpload(@RequestParam("file") MultipartFile[] files) {
        Json json = new Json();
        try {
            if (files == null && files.length == 0) {
                throw new Exception("文件不能为空。");
            }
            ResConfig config = resService.getResConfig("TempUpload");
            if (config == null) {
                throw new Exception("请配置存储路径");
            }
            if (GlobalConstant.USABLE_FILE_SUFFIX_LIST.isEmpty()) {
                throw new Exception("请配置支持的文件后缀");
            }
            List<ResFile> resFiles = saveFile(files);
            if (!resFiles.isEmpty()) {
                List<ResFileVO> responseResTemp = new ArrayList<>();
                for (ResFile res : resFiles) {
                    String suffix = FileTypeUtil.getExtensionName(res.getResName());
                    if (GlobalConstant.USABLE_FILE_SUFFIX_LIST.contains(suffix)) {
                        ResFileVO resFileVO = new ResFileVO();
                        res.setStoreUrl(res.getStoreUrl());
                        ResFile resFileFDB = resService.saveOrUpdResFile(res);
                        resFileFDB.setStoreUrl(config.getAttachUrl() + resFileFDB.getStoreUrl());
                        resFileVO.setResId(resFileFDB.getResId());
                        resFileVO.setStoreUrl(resFileFDB.getStoreUrl());
                        responseResTemp.add(resFileVO);
                    } else {
                        logger.error("文件类型错误");
                    }
                }
                json.setObj(responseResTemp);
            }
            json.setSuccess(true);
            json.setMsg("success");
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }
        return json;
    }

    private List<ResFile> saveFile(MultipartFile[] files) {
        return this.saveFileToLocal(files);
    }

    private List<ResFile> saveFileToLocal(MultipartFile[] files) {
        List<ResFile> resFiles = new ArrayList<ResFile>();
        for (MultipartFile file : files) {
            ResFile resource = null;
            if (!file.isEmpty()) {
                try {
                    resource = new ResFile();
                    String currentDate = DateUtil.getFormattedDate(new Date(), "yyyyMMdd");
                    String newFileName = generateUUIDFileName(file.getOriginalFilename());
                    String filePath = Configure.getFileDir() + "/" + currentDate + "/";
                    File fileDir = new File(filePath);
                    if (!fileDir.exists()) {
                        fileDir.mkdirs();
                    }
                    String fileFullName = filePath + System.getProperty("file.separator") + newFileName;
                    // 转存文件
                    String resType = FileTypeUtil.getFileSuffix(fileFullName);
                    file.transferTo(new File(fileFullName));
                    logger.info("-------------->>>转存到地址:" + fileFullName);
                    //若文件是amr格式的文件，转换为MP3格式，便于前台h5播放音频
//                    if (fileFullName.endsWith("amr")) {
//                        String mp3FullName = fileFullName.replace("amr", "mp3");
//                        FFMpegUtil ffMpegUtil = new FFMpegUtil(Configure.getFfmpegDir(), fileFullName);
//                        ffMpegUtil.audioToMp3(mp3FullName);
//                        fileFullName = mp3FullName;
//                    }
//                    int w = FileUtil.getImgWidth(new File(fileFullName));
//                    int h = FileUtil.getImgHeight(new File(fileFullName));
//                    resource.setW(String.valueOf(w));
//                    resource.setH(String.valueOf(h));
                    resource.setSize(file.getSize());
                    resource.setResType(resType);
//                    String mp3Name = newFileName.replace("amr", "mp3");
                    resource.setResName(newFileName);
                    resource.setResOriginalName(file.getOriginalFilename());
                    resource.setStoreDate(currentDate);
                    resource.setStoreSrc("LOCAL");
                    resource.setStoreUrl(filePath + newFileName);
                } catch (Exception e) {
                    logger.error("保存失敗：", e);
                }
            } else {
                continue;
            }
            resFiles.add(resource);
        }
        return resFiles;
    }

    private String generateUUIDFileName(String fileOriginalName) {
        String fileExtensionName = FileTypeUtil.getExtensionName(fileOriginalName);
        String newFileName = UUID.randomUUID().toString();
        if (StringUtils.isNotBlank(fileExtensionName)) {
            newFileName += "." + fileExtensionName;
        }
        return newFileName;
    }
}
